# --**coding:utf-8**--
# author:hemq

from django.shortcuts import render
from django.http import HttpResponse, JsonResponse
from qaStatistic.config import utils, config
from django.views.decorators.csrf import csrf_exempt
# Create your views here.
import paramiko, logging, uuid
from django.views.decorators.http import require_http_methods
from django.views.decorators.csrf import csrf_exempt

logInfo = utils.signLogger('linkface_querylog.log').getInfoLogger()
logErrorInfo = utils.signLogger('linkface_queryLog_error.log').getErrorLogger()


def __queryInterface(serviceIp,interfaceName,date,appID,requestTime,queryType):
    try:
        logInfo.info('begin query interface')
        logid = utils.getLogid()
        logInfo.info('creat log id,the logid is:{0}'.format(logid))
        logInfo.info('requestInfo : serviceIp:{0},interfaceName:{1},date:{2},appID:{3},requestTime:{4},queryType:{5}'.format(serviceIp,interfaceName,date,appID,requestTime,queryType))
        config.interfaceNum['queryType'] = queryType
        if serviceIp in config.ipList.keys():
            info = config.ipList.get(serviceIp)
            sshClient = utils.register(serviceIp, info.get('port'), info.get('user'), info.get('pwd'))
            logFile = utils.queryLogFile(sshClient,config.interPath)
            logInfo.info('logid:{0},find log file,the file name is:{1}'.format(logid,logFile))
            if requestTime == '':  # 无 requestTime
                logInfo.info('logid:{0},requestTime == '',requestTime is {1}, query must conditions'.format(logid,requestTime))
                for code in config.httpCode:
                    commond = utils.queryInterConditions(interfaceName, config.httpCode.get(code),
                                                     config.interPath,logFile,apiID=appID).queryByHttpCodeAndApiID()
                    logInfo.info('logid:{0},the query command is:{1}'.format(logid,commond))
                    stdin, stdout, stderr = sshClient.exec_command(commond)
                    config.interfaceNum['logNum']['log_'+code] = str(stdout.read()).replace('\n','')
                dbObj = utils.queryDB(interfaceName,date,appID).queryDBByMustCon()
                logInfo.info('logid:{0},begin query db'.format(logid))
                for dbInfo in dbObj:
                    config.interfaceNum['dbNum']['db_'+str(dbInfo.response_code)] = str(dbInfo.count)
                config.interfaceNum['logid'] = logid
                logInfo.info('logid:{0},interfaceNum is:{1}'.format(logid,config.interfaceNum))
                config.interfaceNum['code'] = 200
                return config.interfaceNum
            elif requestTime != '':  # 有 requestTime
                logInfo.info("logid:{0},requestTime != '',requestTime is {1}, query all conditions".format(logid,requestTime))
                for i in config.httpCode:
                    commond = utils.queryInterConditions(interfaceName, config.httpCode.get(i),
                                                         config.interPath,logFile,apiID=appID,
                                                         requestTime=requestTime).queryByAllConditions()
                    logInfo.info('logid:{0},the query command is:{1}'.format(logid,commond))
                    stdin, stdout, stderr = sshClient.exec_command(commond)
                    config.interfaceNum['logNum']['log_' + i] = str(stdout.read()).replace('\n', '')
                dbObj = utils.queryDB(interfaceName, date, appID).queryDBByMustCon()
                logInfo.info('logid:{0},begin query db'.format(logid))
                for dbInfo in dbObj:
                    config.interfaceNum['dbNum']['db_' + str(dbInfo.response_code)] = str(dbInfo.count)
                config.interfaceNum['logid'] = logid
                logInfo.info('logid:{0},interfaceNum is:{1}'.format(logid, config.interfaceNum))
                config.interfaceNum['code'] = 200
                return config.interfaceNum
        else:
            logErrorInfo.info('the logid is:{1},ip not exist!,the ip is:{0}'.format(logid,serviceIp))
            config.errorResponse['code'] = 201
            return config.errorResponse
    except Exception as e:
        logErrorInfo.error('function index has Exception:{0}'.format(e))


def __queryChannelInfo(channel,interfaceName,date,queryType):
    try:
        logid = utils.getLogid()
        logInfo.info('logid:{0},begin query channel info')
        logid = utils.getLogid()
        config.interfaceNum['queryType'] = queryType
        logInfo.info('logid:{0},queryType:{1}'.format(logid,queryType))
        info = config.ipList.get(config.channelIp)
        sshClient = utils.register(config.channelIp, info.get('port'), info.get('user'), info.get('pwd'))
        logFile = utils.queryChannelLogFile(sshClient, config.channelPath)
        logInfo.info('logid:{0},find log file,the file name is:{1}'.format(logid, logFile))
        # 没有接口前缀的接口，可以不做处理
        channelShortName = utils.getShortName(channel)
        supplierID = utils.getSupplierId(channel)
        # print 'supplierID', supplierID
        supplierServiceID = utils.getSupplierServicesID(supplierID,interfaceName)
        if supplierServiceID == None:
            logInfo.info('the supplierServices is None,please check!!!')
        # print 'supplierServiceID:', supplierServiceID
        logInfo.info('logid:{0},supplierID:{1},supplierServiceID:{2},channelShortName:{3}'.format(logid,supplierID,supplierServiceID,channelShortName))
        result = utils.queryChannelDB(supplierID, supplierServiceID, date).querySupplierApiStatistics()
        logInfo.info('logid:{0},db --> supplier_api_statistics id is:{1}'.format(logid,result.id))
        config.dbNum.get('dbNum')['invoked_times'] = result.invoked_times
        config.dbNum.get('dbNum')['succedded_times'] = result.succeeded_times
        config.dbNum['code'] = 200
        config.dbNum['queryType'] = queryType
        config.dbNum['logid'] = logid
        command = utils.queryChannelConditions(interfaceName,channelShortName,logFile,date).queryChannelByAllCond()
        logInfo.info('logid:{0},command is:{1}'.format(logid,command))
        stdin, stdout, stderr = sshClient.exec_command(command)
        config.dbNum.get('logNum')['allNum'] = str(stdout.read()).replace('\n', '')
        return config.dbNum

    except Exception as exception:
        logErrorInfo.info('__queryChannelInfo has exception:{0}'.format(exception))
        raise exception

def __queryEncryptInfo(serviceIp,interfaceName,requestid,queryType):
    try:
        returnInfo = {'queryType':'3'}
        logid = utils.getLogid()
        logInfo.info('logid:{0},begin query channel info'.format(logid))
        # logid = utils.getLogid()
        config.interfaceNum['queryType'] = queryType
        logInfo.info('logid:{0},queryType:{1}'.format(logid, queryType))
        if serviceIp in config.ipList.keys():
            info = config.ipList.get(serviceIp)
            sshClient = utils.registerBussiness(serviceIp,info.get('user'), info.get('pwd'))
            logFile = utils.queryBusinessLogFile(sshClient,config.businessPath)
            cloudApiLogFile = utils.queryBusinessCloudApiLogFile(sshClient,config.businessCloudApiPath)
            if logFile is None or cloudApiLogFile is None:
                logInfo.info('logid:{0},logFile not exists,{1},{2}'.format(logid, logFile,cloudApiLogFile))
            else:
                # facade
                logInfo.info('logid:{0},find log file,the file name is:{1},{2}'.format(logid, logFile, cloudApiLogFile))
                command = utils.queryBussinessConditions(config.businessPath, logFile, requestid).queryByRequestId()
                logInfo.info('logid:{0},the query command is:{1}'.format(logid, command))
                stdin, stdout, stderr = sshClient.exec_command(command)
                # print stdout.read()
                returnInfo['facade'] = str(stdout.read())
                # 查业务cloudApi
                command2 = utils.queryBussinessConditions(config.businessPath, cloudApiLogFile,requestid).queryCloudApiByRequestID()
                logInfo.info('logid:{0},the query command is:{1}'.format(logid, command2))
                stdin, stdout, stderr = sshClient.exec_command(command2)
                returnInfo['cloud'] = str(stdout.read())
                print stdout.read()
            info = config.ipList.get('100.66.225.5')
            sshClient2 = utils.register('100.66.225.5', info.get('port'), info.get('user'), info.get('pwd'))
            cloudApiLogFile_225 = utils.queryLogFile(sshClient2, config.interPath) # cloud api path
            cloudFacadeLogFile_225 = utils.queryChannelLogFile(sshClient2, config.channelPath) # cloud-facade path
            if cloudApiLogFile_225 is None or cloudFacadeLogFile_225 is None:
                logInfo.info('logid:{0},225-logFile not exists,{1},{2}'.format(logid,cloudApiLogFile_225,cloudFacadeLogFile_225))
            else:
                logInfo.info('logid:{0},225-find log file,the file name is:{1},{2}'.format(logid, cloudApiLogFile_225,
                                                                                       cloudFacadeLogFile_225))
                # cha 225
                print '225 cloudapi'
                stdin, stdout, stderr = sshClient2.exec_command(utils.queryBussinessConditions(config.businessPath,cloudApiLogFile_225,requestid).query225CloudApiByReqestID())
                returnInfo['cloud_225'] = str(stdout.read())
                print '225 cloudfacade'
                stdin, stdout, stderr = sshClient2.exec_command(utils.queryBussinessConditions(config.businessPath, cloudFacadeLogFile_225,requestid).query225CloudFacadeByReqestID())
                returnInfo['facade_225'] = str(stdout.read())
            return returnInfo
        else:
            logErrorInfo.info('the logid is:{1},ip not exist!,the ip is:{0}'.format(logid, serviceIp))
            config.errorResponse['code'] = 201
            return config.errorResponse

    except Exception as exception:
        logErrorInfo.info('__queryEncryptInfo has exception:{0}'.format(exception))



def getIndex(request):

    return render(request, 'view/index.html')

@csrf_exempt
def getSubValue(request):
    optionsRadiosinline = request.POST.get('optionsRadiosinline')
    print optionsRadiosinline
    if optionsRadiosinline == config.queryContent.get('interface'):
        serviceIp = request.POST.get('ip')
        interfaceName = request.POST.get('interfacename')
        date = request.POST.get('date')
        appID = request.POST.get('apiid')
        requestTime = request.POST.get('requesttime')
        checkResult = utils.checkInterfaceParms(serviceIp,interfaceName,date,appID) # check
        if checkResult == True:
            queryResult = __queryInterface(serviceIp,interfaceName,date,appID,requestTime,optionsRadiosinline) # excute query
            return JsonResponse(queryResult)
        else:
            return JsonResponse(checkResult)

    elif optionsRadiosinline == config.queryContent.get('channel'):
        channelName = request.POST.get('channelname')
        interfaceName = request.POST.get('interfacename')
        date = request.POST.get('date')
        checkResult = utils.checkChannelParms(channelName,interfaceName,date) # check
        if checkResult==True:
            result = __queryChannelInfo(channelName,interfaceName,date,optionsRadiosinline) # excute query
            return JsonResponse(result)
        else:
            return JsonResponse(checkResult)
    elif optionsRadiosinline == config.queryContent.get('encryption'):
        print 'optionsRadiosinline:', optionsRadiosinline
        serviceIp = request.POST.get('ip')
        interfaceName = request.POST.get('interfacename')
        requestid = request.POST.get('requestid')
        result = __queryEncryptInfo(serviceIp,interfaceName,requestid,optionsRadiosinline)
        return JsonResponse(result)
        # return render(request,'view/EncryptInfo.html',{'result':result})

    return JsonResponse({'code': 200, 'result': 'success'})
